package com.qdevelop.control.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.qdevelop.control.action.LoginAction;
import com.qdevelop.control.bean.SecurityUserBean;
import com.qdevelop.model.utils.UtilsFactory;
import com.qdevelop.security.SecurityFactory;

public class SecurityInterceptor extends AbstractInterceptor{
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		UtilsFactory.init();
		if(UtilsFactory.isInterceptor){
			String _url = getRequestUrl(ServletActionContext.getRequest());
			LoginAction.setFocusUrl(_url);
			SecurityUserBean user = LoginAction.getLoginUserRoles();
			if (user == null&&!LoginAction.validatorUser(user)) {
				return Action.LOGIN;
			}
			SecurityFactory.getInstance().securityURLControl(_url, user);
		} 
		return invocation.invoke();
	}

	private String getRequestUrl(HttpServletRequest request){
		if(request==null){return null;}
		if(request.getQueryString() !=null){
			return (request.getRequestURL().toString() +  "?" + request.getQueryString());
		}else{
			return  request.getRequestURL().toString();
		}
	}

}
